#include "eventfilter.h"

#include <QWidget>
#include <QApplication>
#include <QDebug>

EventFilter::EventFilter(QObject *parent) : QObject(parent), m_enabled(true)
{
}

void EventFilter::setEnabled(bool enabled)
{
	m_enabled = enabled;
}

void EventFilter::setIgnoredWindows(const QList<QWidget *> &windows)
{
	m_ignoredWindows = windows;
}

bool EventFilter::eventFilter(QObject *obj, QEvent *event)
{
	if (!m_enabled || shouldIgnore(obj))		return QObject::eventFilter(obj, event);	// 忽略的情况就直接回父类
	// 键盘
	if (event->type() == QEvent::KeyPress) {
		QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        emit keyPressed(keyEvent);
	} else if (event->type() == QEvent::KeyRelease) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        emit keyReleased(keyEvent);
    } 
	// 鼠标
	else if (event->type() == QEvent::MouseButtonPress) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        emit mousePressed(mouseEvent);
    } else if (event->type() == QEvent::MouseButtonRelease) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        emit mouseReleased(mouseEvent);
    } else if (event->type() == QEvent::MouseMove) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        emit mouseMoved(mouseEvent);
    }
	// 焦点
	else if (event->type() == QEvent::FocusIn) {
		QWidget* widget = qobject_cast<QWidget*>(obj);
		if (widget)		emit focusChanged(QApplication::focusWidget(), widget);
	}
	// 返回false表示继续传递事件
	return QObject::eventFilter(obj, event);
}

bool EventFilter::shouldIgnore(QObject *obj) const
{
	// check window should ignore
	QWidget* widget = qobject_cast<QWidget*>(obj);
	if (widget && m_ignoredWindows.contains(widget))	return true;

	// 我们自己的候选词窗口或设置窗口等
	if (widget) {
		QString className = widget->metaObject()->className();
		return (className.contains("CandidateWindow") || className.contains("SettingsDialog") || className.contains("NumpadPanel")) ? true : false;
	}
	return false;
}
